var failed=success=queue=runningCount=createCount=vmIndex=0,start=null,countdown=require('./countdown'),sdc = require('sdc-clients'),dc_config=require('./config')['poc'],vmapi = new sdc.VMAPI(dc_config.vmapi),readline = require('readline'),rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
}),_per=0,vm_num=0,retry=0,
defaults=require('./config').defaults

//rl.question('请输入 owner_uuid('+defaults.owner_uuid.name+'):\n', function(user_id) {
	//rl.question('请输入并发数(默认等于vm_num):\n', function(per) {
		//rl.close()
		user_id=0,per=0
		user_id=user_id||defaults.owner_uuid.id
		if(!user_id)return console.log('!!!!!!!!!!owner_uuid 不能为空!!!')
		_per=per=per||15
		start=new Date()
		vmapi.listVms({query:"(&(state=running)(server_uuid=44454c4c-3900-105a-8043-b1c04f313232))"},function(err, vms){//(&(|(state=running)(state=stopped))(owner_uuid="+user_id+"))
			var QDate=new Date()
			console.log('\n~~~~~~~~查询主机列表，api响应时间：',countdown(QDate,start,countdown.MILLISECONDS).toString(),'('+start.getTime()+'~'+QDate.getTime()+')\n')
			if (err)console.log(err)
			else if(vms.length){
				vm_num=vms.length
				console.log('\n待删除主机数：',vm_num)
				createCount=runningCount=vms.length
				if(parseInt(per)>0&&parseInt(createCount)>parseInt(per)){
					queue=createCount-per
					createCount=per
					console.log('有'+queue+'台主机进入等待队列！')
				}
				start=new Date()
				serializeDelete(vms,user_id)
			}else{
				console.log('主机列表为空')
				//process.exit(1)
			}
		})
	//})
//})
function serializeDelete(vms,user_id){
	//if(createCount){
		var begin=new Date(),uuid=vms.pop().uuid
		vmapi.deleteVm({creator_uuid:user_id,uuid:uuid},function (err, obj) {
			var end=new Date()
			if(--createCount)serializeDelete(vms,user_id)
			var presentCount=++vmIndex
			if(err){
				errs(err,presentCount,uuid)
				deleteVM(vms,user_id)
			}
			else{
				console.log('\n序列化创建第'+presentCount+'项任务，api响应时间：',countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),'('+begin.getTime()+'~'+end.getTime()+')')
				setTimeout(function(){cometState(obj,'',vms,user_id,begin,presentCount)},500)
			}
		})
	//}
}
function deleteVM(vms,user_id){
	//if(vms.length){
		var begin=new Date(),uuid=vms.pop().uuid
		vmapi.deleteVm({creator_uuid:user_id,uuid:uuid},function (err, obj) {
			var end=new Date()
			if(err){
				errs(err,++_per,uuid)
				deleteVM(vms,user_id)
			}else{
				console.log('\n序列化创建第'+(++_per)+'项任务，api响应时间：',countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),'('+begin.getTime()+'~'+end.getTime()+')')
				var presentCount=_per
				setTimeout(function(){cometState(obj,'',vms,user_id,begin,presentCount)},500)
			}
		})
	//}
}
function errs(err,index,uuid){
	if(err.body&&err.body.errors)
		for(var e in err.body.errors)
			console.error('!!!!!!!!!!第'+index+'项任务无法创建',err.body.errors[e],uuid)
	else console.error('!!!!!!!!!!第'+index+'项任务无法创建',err,uuid)
}
var http = require('http');
function cometState(obj,state,vms,user_id,begin,presentCount){
	var options = {
		hostname: dc_config.workflow, 
		path: '/jobs/'+obj.job_uuid,
		method: 'GET',
		headers: {"Accept": "application/json"}
	};
	var req = http.request(options, function (res) {
		var body = '';
		res.setEncoding('utf8');
		res.on('data',function(d){
			body += d;
		}).on('end', function(){
			var jobState=JSON.parse(body).execution
			if(jobState==="succeeded"||jobState==="failed"||jobState==="canceled"){
					var end=new Date()
						vmapi.getVm({uuid:obj.vm_uuid},function(err, vm){
							if(vm.state!=='running'&&vm.state!=='stopped'){
								--runningCount
								console.log('\n第'+presentCount+'台主机删除成功,耗时:',countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),jobState,vm.state,++success,'('+begin.getTime()+'~'+end.getTime()+')')
								if(queue){
									--queue
									deleteVM(vms,user_id)
								}
								if(!runningCount){
									console.log('\n\n~~~~~~~所有'+vm_num+'台主机删除完毕，成功'+success+'台，重试'+failed+'次，总耗时：',countdown(end,start,countdown.SECONDS | countdown.MILLISECONDS).toString(),'('+start.getTime()+'~'+end.getTime()+')\n\n')
									//process.exit(1)
								}
							}else{
								//++queue;
								//++retry
								vms.push({uuid:obj.vm_uuid})
								console.error('\n!!!!!!!!!!第'+presentCount+'台主机删除失败,已加入重试队列！耗时:',countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),jobState,vm.state,++failed,'('+begin.getTime()+'~'+end.getTime()+')')
								if(failed>=vm_num){
									console.error('!!!!!!!!!!!!!!!!!!!!所有主机进入重试队列！系统杯具了？！')
									//process.exit(1)
								}else deleteVM(vms,user_id)
							}
						})
			}else setTimeout(function(){cometState(obj,state,vms,user_id,begin,presentCount)},500)
		});
	}).on('error', function(e) {
		console.error('\n!!!!!!!!!!查询第'+presentCount+'项任务进度异常：' + e.message);
	})
	req.end();
}